package com.delaphone.flocash.web.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

/**
 *
 * @author tamdx
 */
public class Captcha extends HttpServlet {

    public static final String CAPTCHA_KEY = "Captcha";
    public static final Logger log = Logger.getLogger("Captcha");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, IOException, IOException {

        int width = 170, height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        Random r = new Random();
        String token = Long.toString(Math.abs(r.nextLong()), 36);
        String ch = token.substring(0, 4);
        g.setColor(Color.BLACK);
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, width, height);
        Font font = new Font("Verdana", Font.HANGING_BASELINE, 35);
        g.setFont(font);
        ch = ch.toUpperCase();
        g.drawString(ch, 35, 30);

        int dh = image.getHeight() / 8;
        int dw = image.getWidth() / 10;
        g.setColor(new Color(52, 126, 188));
        for (int i = 0; i < 10; i++) {
            g.drawLine(0, i * dh, image.getWidth(), i * dh);
        }
        g.drawLine(0, image.getHeight(), image.getWidth(), image.getHeight());
        for (int i = 0; i < image.getWidth() / dh; i++) {
            g.drawLine(i * dh, 0, i * dh, image.getHeight());
        }

        g.dispose();
        HttpSession session = request.getSession();

        session.setAttribute(CAPTCHA_KEY, ch);

        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpeg", outputStream);
        outputStream.close();
    }
}
